import random
import re
import string
import time
import jwt
import redis as redis
from captcha.image import ImageCaptcha
from django.contrib.auth.hashers import check_password,make_password
from django.http import HttpResponse
from rest_framework.views import APIView
from OAsystem import settings
from user.check_jwt import check_userjwt
from user.models import User, Department, Rank, Position, Role, Menu, Salary
from rest_framework.response import Response
from user.serializer import UserSer, DepSer, RankSerializer, PositionSerializer, RoleSer, MenuSer, SalarySer


# 校验用户名
class CheckName(APIView):
    def get(self, request, name):
        if not name:
            return Response({"msg": "用户名获取失败", "oode": 400})
        try:
            User.objects.get(name=name)
            return Response({"msg": "用户已存在", "code": 400})
        except Exception as e:
            return Response({"msg": "ok", "code": 200})


# 校验手机号
class CheckMobile(APIView):
    def get(self, request, mobile):
        if not mobile:
            return Response({"msg": "手机号获取失败", "oode": 400})
        try:
            User.objects.get(mobile=mobile)
            return Response({"msg": "用户已存在", "code": 400})
        except Exception as e:
            return Response({"msg": "ok", "code": 200})


# 登录
class Reg_Log(APIView):
    def post(self, request):
        name = request.data.get("name")
        password = request.data.get('password')
        mobile = request.data.get("mobile")
        rule = r"^1[3-9][0-9]+$"
        if not re.findall(rule, mobile):
            return Response({"code": 400, "msg": "手机号格式错误"})
        if not all([name, mobile, password]):
            return Response({"code": 400, "msg": "请补全登录信息"})
        user_info = User.objects.filter(mobile=mobile).first()
        check_pwd = check_password(password, user_info.user_password)
        # if not check_pwd:
        #     return Response({"msg": "密码错误", "code": 400})
        # if not user_info:
        #     user_info = User.objects.create(user_name=name, user_password=password, mobile=mobile)
        #     payload = {'id': user_info.id, 'name': user_info.name, 'time': int(time.time()) + 4800}
        #     token = jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256')
        #     return Response({"code": 200, "msg": "注册并登录成功", "user": {"name": user_info.name}, "token": token})
        if check_pwd:
            payload = {'id': user_info.id, 'name': user_info.user_name, 'time': int(time.time()) + 4800}
            token = jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256')
            return Response({"code": 200, "msg": "登录成功", "user": {"name": user_info.user_name}, "token": token})
        else:
            return Response({"code": 400, "msg": "登录失败"})


# 重置密码
class Reset_Pwd(APIView):
    def put(self,request):
        # 前端获取手机号 密码 确认密码
        mobile = request.data.get('mobile')
        new_pwd = request.data.get('new_pwd')
        two_pwd = request.data.get('two_pwd')
        user_info = User.objects.filter(mobile=mobile).first()
        if not user_info:
            return Response({
                'code':400,
                'msg':'用户不存在'
            })

        if new_pwd != two_pwd:
            return Response({
                'code':400,
                'msg':'密码不正确 请重新输入'
            })
        check_pwd = make_password(new_pwd)  # 加密
        User.objects.update(user_password = check_pwd)
        return Response({
            'code':200,
            'msg':'密码修改成功'
        })


# 图片验证码
class Img_Verify(APIView):
    def get(self, request, img_id):
        code = ''.join(random.sample(string.ascii_letters + string.digits, 4))
        img = ImageCaptcha()
        image = img.generate(code)
        # 写入redis 后期校验
        redis_cli = redis.Redis(host='localhost',port=6379)
        redis_cli.setex('img_%s'%img_id,60,code)
        redis_cli.close()
        return HttpResponse(image, content_type="image/png")


# 校验图片验证码
class CheckImage(APIView):
    def get(self,request):
        uuid = request.query_params.get('imageCodeID')
        code = request.query_params.get('imageCode')
        redis_cli = redis.Redis(host='localhost',port=6379)
        image_code = redis_cli.get('img_%s'%uuid)
        if image_code:
            if image_code.decode().lower() != code.lower():
                return Response({'msg':'验证码输入错误'})
            else:
                return Response({'code':200})
        else:
            return Response({'msg':'验证码错误'})



# 新增用户 展示用户
class UserApiView(APIView):
    def post(self, request):
        user_name = request.data.get("user_name")
        user_account = request.data.get("user_account")
        user_password = request.data.get("user_password")
        mobile = request.data.get("mobile")
        role_id_id = request.data.get("role_id_id")
        position_id_id = request.data.get("position_id_id")
        rank_id_id = request.data.get("rank_id_id")
        department_id_id = request.data.get("department_id_id")
        if not ([user_name, user_account, mobile, role_id_id, position_id_id, rank_id_id, department_id_id]):
            return Response({"code": 400, "msg": "添加用户信息不完整"})
        user = User.objects.create(user_name=user_name, user_account=user_account, mobile=mobile,
                                   role_id_id=role_id_id, position_id_id=position_id_id, rank_id_id=rank_id_id,
                                   department_id_id=department_id_id)
        user.save()
        return Response({"code": 200, "msg": "添加用户成功"})

    def get(self, request):
        user_name = request.data.get("user_name")
        name = User.objects.filter(user_name=user_name).first()
        if not name:
            return Response({"code": 400, "msg": "无权限"})
        else:
            token = request.headers.get("Token")
            payload = check_userjwt(token)
            if not payload:
                return Response({"code": 401, "msg": "请先登录"})
            user = User.objects.all()
            user_list = []
            for i in user:
                a = {
                    "user_name": i.user_name,
                    "user_account": i.user_account,
                    "user_password": i.user_password,
                    "mobile": i.mobile,
                    "role_id_id": i.role_id_id,
                    "position_id_id": i.position_id_id,
                    "rank_id_id": i.rank_id_id,
                    "department_id_id": i.department_id_id
                }
                user_list.append(a)
            return Response({"code": 200, "msg": "获取成功", 'data': user_list})

class UserOneView(APIView):
    def get(self, request, pk):
        token = request.headers.get("Token")
        payload = check_userjwt(token)
        if not payload:
            return Response({"code": 401, "msg": "请先登录"})
        user = User.objects.filter(id=pk).first()
        ser = UserSer(user)
        return Response({"code": 200, "msg": "获取成功", "data": ser.data})

    def delete(self, request, pk):

        token = request.headers.get("Token")
        payload = check_userjwt(token)
        if not payload:
            return Response({"code": 401, "msg": "请先登录"})
        User.objects.filter(id=pk).delete()
        return Response({"code": 200, "msg": "删除成功"})

    def put(self, request, pk):
        token = request.headers.get("Token")
        payload = check_userjwt(token)
        if not payload:
            return Response({"code": 401, "msg": "请先登录"})
        user = User.objects.filter(id=pk).first()
        ser = UserSer(instance=user, data=request.data)
        ser.is_valid(raise_exception=True)
        ser.save()
        return Response({'code': 200, 'msg': '更新成功'})


# 部门
class DepartmentAPIView(APIView):
    # 获取所有部门数据
    def get(self, request):
        Depart = Department.objects.all()
        ser = DepSer(Depart, many=True)
        return Response(ser.data, status=200)


        # 添加一个
    def post(self, request):
        name = request.data.get("dep_name")
        dep = Department.objects.filter(dep_name=name)
        if dep:
            return Response({'msg': '部门存在', 'code': 400})

        # 继续添加,实例化一个序列化器对象
        ser = DepSer(data=request.data)

        # 数据校验
        if ser.is_valid():
            # 校验通过 保存数据  create
            ser.save()
            return Response({"code": 200, "msg": "成功"})
        else:
            return Response({"error": ser.errors, "code": 400})


# 职级
class RankInfoView(APIView):
    # 获取全部职级
    def get(self,request):
        token = request.headers.get("Token")
        payload = check_userjwt(token)
        if not payload:
            return Response({"code": 401, "msg": "请先登录"})
        rank = Rank.objects.all()
        ser = RankSerializer(rank,many=True)
        return Response({'code':200,'msg':ser.data})

    # 添加职级
    def post(self,request):
        rank_name = request.data.get('name')
        remark = request.data.get('remark')
        rank = Rank.objects.create(rank_name=rank_name,remark=remark)
        rank.save()
        return Response({'code':200,'msg':'添加成功'})

class RankOneView(APIView):
    def get(self, request, rank_id):
        token = request.headers.get("Token")
        payload = check_userjwt(token)
        if not payload:
            return Response({"code": 401, "msg": "请先登录"})
        rank = Rank.objects.filter(id=rank_id).first()
        ser = RankSerializer(rank)
        return Response({"code": 200, "msg": "获取成功", "data": ser.data})

    def delete(self, request, rank_id):
        token = request.headers.get("Token")
        payload = check_userjwt(token)
        if not payload:
            return Response({"code": 401, "msg": "请先登录"})
        Rank.objects.filter(id=rank_id).delete()
        return Response({"code": 200, "msg": "删除成功"})


    def put(self, request, rank_id):
        token = request.headers.get("Token")
        payload = check_userjwt(token)
        if not payload:
            return Response({"code": 401, "msg": "请先登录"})
        rank = Rank.objects.filter(id=rank_id).first()
        ser = RankSerializer(instance=rank, data=request.data)
        ser.is_valid(raise_exception=True)
        ser.save()
        return Response({'code': 200, 'msg': '更新成功'})


# 岗位
class PositionInfoView(APIView):
    # 获取全部岗位
    def get(self, request):
        token = request.headers.get("Token")
        payload = check_userjwt(token)
        if not payload:
            return Response({"code": 401, "msg": "请先登录"})
        position = Position.objects.all()
        ser = PositionSerializer(position,many=True)
        return Response({'code': 200, 'msg': ser.data})

    # 添加岗位
    def post(self, request):
        position_name = request.data.get('name')
        remark = request.data.get('remark')
        rank = Position.objects.create(rank_name=position_name, remark=remark)
        rank.save()
        return Response({'code': 200, 'msg': '添加成功'})

class PositionOneView(APIView):
    def get(self, request, position_id):
        token = request.headers.get("Token")
        payload = check_userjwt(token)
        if not payload:
            return Response({"code": 401, "msg": "请先登录"})
        position = Position.objects.filter(id=position_id).first()
        ser = PositionSerializer(position)
        return Response({"code": 200, "msg": "获取成功", "data": ser.data})

    def delete(self, request, position_id):
        token = request.headers.get("Token")
        payload = check_userjwt(token)
        if not payload:
            return Response({"code": 401, "msg": "请先登录"})
        Position.objects.filter(id=position_id).delete()
        return Response({"code": 200, "msg": "删除成功"})


    def put(self, request, position_id):
        token = request.headers.get("Token")
        payload = check_userjwt(token)
        if not payload:
            return Response({"code": 401, "msg": "请先登录"})
        position = Position.objects.filter(id=position_id).first()
        ser = PositionSerializer(instance=position, data=request.data)
        ser.is_valid(raise_exception=True)
        ser.save()
        return Response({'code': 200, 'msg': '更新成功'})


# 角色
class RoleView(APIView):
    def get(self,request):
        token = request.headers.get("Token")
        payload = check_userjwt(token)
        if not payload:
            return Response({"code": 401, "msg": "请先登录"})
        role = Role.objects.all()
        ser = RoleSer(role,many=True)
        return Response({'code': 200, 'msg': ser.data})

    def post(self, request):
        role_name = request.data.get('role_name')
        remark = request.data.get('remark')
        menu_me_urls = request.data.get("menu_me_urls")
        role = Role.objects.create(role_name=role_name, remark=remark,menu_me_urls=menu_me_urls)
        role.save()
        return Response({'code': 200, 'msg': '添加成功'})

class RoleOneView(APIView):
    def get(self, request, role_id):
        token = request.headers.get("Token")
        payload = check_userjwt(token)
        if not payload:
            return Response({"code": 401, "msg": "请先登录"})
        role = Role.objects.filter(id=role_id).first()
        ser = RoleSer(role)
        return Response({"code": 200, "msg": "获取成功", "data": ser.data})

    def delete(self, request, role_id):
        token = request.headers.get("Token")
        payload = check_userjwt(token)
        if not payload:
            return Response({"code": 401, "msg": "请先登录"})
        Role.objects.filter(id=role_id).delete()
        return Response({"code": 200, "msg": "删除成功"})

    def put(self, request, role_id):
        token = request.headers.get("Token")
        payload = check_userjwt(token)
        if not payload:
            return Response({"code": 401, "msg": "请先登录"})
        role = Role.objects.filter(id=role_id).first()
        ser = RoleSer(instance=role, data=request.data)
        ser.is_valid(raise_exception=True)
        ser.save()
        return Response({'code': 200, 'msg': '更新成功'})


# 菜单
class MenuView(APIView):
    def get(self,request):
        token = request.headers.get("Token")
        payload = check_userjwt(token)
        if not payload:
            return Response({"code": 401, "msg": "请先登录"})
        menu = Menu.objects.all()
        ser = MenuSer(menu,many=True)
        return Response({'code': 200, 'msg': ser.data})
    def post(self,request):
        menu_name = request.data.get("menu_name")
        menu_url = request.data.get("menu_url")
        menu_icon = request.data.get("menu_icon")
        menu_me_id = request.data.get("menu_me_id")
        remark = request.data.get("remark")
        sort = request.data.get("sort")
        menu = Menu.objects.create(menu_name=menu_name, menu_url=menu_url,menu_icon=menu_icon,menu_me_id=menu_me_id,remark=remark,sort=sort)
        menu.save()
        return Response({'code': 200, 'msg': '添加成功'})

class MenuOneView(APIView):
    def get(self, request, menu_id):
        token = request.headers.get("Token")
        payload = check_userjwt(token)
        if not payload:
            return Response({"code": 401, "msg": "请先登录"})
        menu = Menu.objects.filter(id=menu_id).first()
        ser = MenuSer(menu)
        return Response({"code": 200, "msg": "获取成功", "data": ser.data})
    def delete(self, request, menu_id):
        token = request.headers.get("Token")
        payload = check_userjwt(token)
        if not payload:
            return Response({"code": 401, "msg": "请先登录"})
        Menu.objects.filter(id=menu_id).delete()
        return Response({"code": 200, "msg": "删除成功"})

    def put(self, request, menu_id):
        token = request.headers.get("Token")
        payload = check_userjwt(token)
        if not payload:
            return Response({"code": 401, "msg": "请先登录"})
        menu = Menu.objects.filter(id=menu_id).first()
        ser = MenuSer(instance=menu, data=request.data)
        ser.is_valid(raise_exception=True)
        ser.save()
        return Response({'code': 200, 'msg': '更新成功'})


# 工资表
class SalaryView(APIView):
    def post(self,request):
        name = request.data.get("name")
        user_id_id = request.data.get("user_id_id")
        attendance = request.data.get("attendance")
        industrial_mining = request.data.get("industrial_mining")
        ask_leave = request.data.get("ask_leave")
        basic_wage = request.data.get("basic_wage")
        wage_jobs = request.data.get("wage_jobs")
        sala = Salary.objects.create(name=name,user_id_id=user_id_id,attendance=attendance,industrial_mining=industrial_mining,ask_leave=ask_leave,basic_wage=basic_wage,wage_jobs=wage_jobs)
        sala.save()
        return Response({"code":200,"msg":"添加成功"})
    def get(self,request):
        token = request.headers.get("Token")
        payload = check_userjwt(token)
        if not payload:
            return Response({"code": 401, "msg": "请先登录"})
        sala = Salary.objects.all()
        ser = SalarySer(sala,many=True)
        return Response({'code': 200, 'msg': ser.data})



class SalaryOneView(APIView):
    def get(self,request,salary_id):
        token = request.headers.get("Token")
        payload = check_userjwt(token)
        if not payload:
            return Response({"code": 401, "msg": "请先登录"})
        salary = Salary.objects.filter(id=salary_id)
        ser = SalarySer(salary,many=True)
        return Response({"code":200,"msg":"获取成功","data":ser.data})

    def put(self,request,salary_id):
        token = request.headers.get("Token")
        payload = check_userjwt(token)
        if not payload:
            return Response({"code": 401, "msg": "请先登录"})
        salary = Salary.objects.filter(id=salary_id).first()
        ser = SalarySer(instance=salary, data=request.data)#用于序列化时，将模型类对象传入 instance 参数；用于反序列化时，将要被反序列化的数据传入 data 参数；
        ser.is_valid(raise_exception=True)# raise_exception=True 的含义是，一旦检出错误，自动return，不用我们手写return
        ser.save()
        return Response({'code': 200, 'msg': '更新成功'})

    def delete(self,request,salary_id):
        token = request.headers.get("Token")
        payload = check_userjwt(token)
        if not payload:
            return Response({"code": 401, "msg": "请先登录"})
        Salary.objects.filter(id=salary_id).delete()
        return Response({"code":200,"msg":"删除成功"})




